package com.tangkun.environment.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.URLUtil;

import com.tangkun.environment.R;
import com.tangkun.environment.application.Session;
import com.tangkun.environment.entity.login.UpDateInfo;
import com.tangkun.environment.entity.token.LoginReturn;
import com.tangkun.environment.network.GlobalUrl;
import com.tangkun.environment.network.MySubscribe;
import com.tangkun.environment.rx.RxActivityHelper;
import com.tangkun.environment.service.SoftwareService;
import com.tangkun.environment.utils.JumpHelper;
import com.tangkun.environment.utils.LogUtils;
import com.tangkun.environment.utils.ProgressDialogUtils;
import com.tangkun.environment.utils.SharePrefercesUtils;
import com.tangkun.environment.utils.Utils;
import com.tangkun.environment.view.CommonDialog;
import com.tangkun.environment.view.CommonQueDingDialog;
import com.tangkun.environment.view.TipsDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import butterknife.ButterKnife;


/**
 * 欢迎页面
 */
public class SplashActivity extends BaseActivity {
    private Context mContext;

    ProgressDialog proD;
    boolean isForceUpdate = false;
    private boolean isCancel = false;// 判断下载文件时，是否点击取消按钮，避免取消以后还继续下载
    private String VersonName = "environment.apk";// 临时存放的文件名

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);
        //检测版本是否有更新
        checkVersion();
    }

    /**
     * 登录
     */
    private void login() {
        //调用登录接口，成功后跳转主页面MainActivity
        String username = SharePrefercesUtils.getUserName(SplashActivity.this);//手机号
        String password = SharePrefercesUtils.getPassword(SplashActivity.this);//密码
        fromNetwork.login(username, password).compose(new RxActivityHelper<LoginReturn>().ioMain(SplashActivity.this, false))
                .subscribe(new MySubscribe<LoginReturn>(mContext, false) {

                    @Override
                    protected void success(LoginReturn resultBean) {
                        if (resultBean.data != null) {
                            //本地文件存储用户已登录
                            SharePrefercesUtils.setLoginStatus(mContext, true);
                            LogUtils.e("authmark:" + resultBean.data.authmark);
                            //刷新本地token
                            SharePrefercesUtils.setToken(mContext, resultBean.data.authmark);
                            //更新用户信息
                            Session.getInstance().setUserInfo(resultBean.data);
                            //是否绑定
                            if (resultBean.data.bindlist == null || resultBean.data.bindlist.size() == 0) {
                                SharePrefercesUtils.setBindStatus(mContext, false);
                            } else {
                                SharePrefercesUtils.setBindStatus(mContext, true);
                            }
                            //跳转主页
                            JumpHelper.jump(SplashActivity.this, MainActivity.class);
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage);
                        //报错后跳转登录页面
                        JumpHelper.jump(SplashActivity.this, IndexActivity.class, true);
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 检测版本是否有更新
     */
    private void checkVersion() {
        fromNetwork.versionAndroid().compose(new RxActivityHelper<UpDateInfo>().ioMain(SplashActivity.this, false))
                .subscribe(new MySubscribe<UpDateInfo>(mContext, false) {
                    @Override
                    protected void success(UpDateInfo upDateInfo) {
                        if (upDateInfo.data != null) {
                            getApkSuccess(upDateInfo.data);
                        } else {
                            versionCheckFinished(true);
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage);
                        versionCheckFinished(true);
                    }
                });
    }

    /**
     * 版本升级更新处理方法
     */
    public void getApkSuccess(final UpDateInfo.ResultBean bean) {
        if (bean != null) {
            if (!Utils.getVersionName(SplashActivity.this).equals(bean.num)) {
                if (bean.forced == 1) {// 强制升级
                    if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())) {// 如果SDCard存在
                        isForceUpdate = true;
                        CommonQueDingDialog dialog = new CommonQueDingDialog(SplashActivity.this, "应用升级", TextUtils.isEmpty(bean.description) ? "请点击确定按钮升级" : bean.description);
                        dialog.show();
                        dialog.setOnClickListener(new CommonQueDingDialog.OnClickListener() {

                            @Override
                            public void rightClick() {
                                // 创建对话框来显示下载进度
                                proD = ProgressDialogUtils.getProgressDialog(SplashActivity.this);
                                proD.setTitle(R.string.dialog_title);
                                proD.setMessage(getResources().getString(R.string.upgrading));
                                proD.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                                proD.setCancelable(false);// 设置下载进度总可以取消
                                proD.setOnKeyListener(new DialogInterface.OnKeyListener() {

                                    @Override
                                    public boolean onKey(DialogInterface arg0, int arg1, KeyEvent arg2) {
                                        // TODO Auto-generated method
                                        // stub
                                        return true;
                                    }
                                });
                                proD.setProgress(0);// 设置初始进度为0
                                proD.incrementProgressBy(1);// 设置每次增加1

                                // 判断路径是否正确
                                if (URLUtil.isNetworkUrl(bean.url)) {
                                    if (!(Environment.getExternalStorageState()).equals(Environment.MEDIA_MOUNTED)) {
                                        isForceUpdate = false;
                                        TipsDialog tipsDialog = new TipsDialog(SplashActivity.this, "SDCard不存在,无法下载文件!");
                                        tipsDialog.show();
                                    } else {
                                        // 传入下载apk路径进行下载 示例网络路径
                                        downFile(bean.url);
                                    }
                                } else {
                                    isForceUpdate = false;
                                    TipsDialog tipsDialog = new TipsDialog(SplashActivity.this, "无法读取文件!");
                                    tipsDialog.show();
                                }
                            }
                        });
                    } else {
                        TipsDialog tipsDialog = new TipsDialog(SplashActivity.this, "SDCard不存在，无法下载新版本");
                        tipsDialog.show();
                    }
                } else {// 非强制升级
                    if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())) {// 如果SDCard存在
                        CommonDialog dialog = new CommonDialog(SplashActivity.this, "应用升级", TextUtils.isEmpty(bean.description) ? "请点击确定按钮升级" : bean.description);
                        dialog.show();
                        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {

                            @Override
                            public boolean onKey(DialogInterface arg0, int arg1, KeyEvent arg2) {
                                return true;
                            }
                        });
                        dialog.setOnClickListener(new CommonDialog.OnClickListener() {
                            @Override
                            public void leftClick() {
                                versionCheckFinished(true);
                            }

                            @Override
                            public void rightClick() {
                                toStartService(bean);
                                versionCheckFinished(true);
                            }
                        });
                    } else {// 不是强制升级且没有SDCard时不做任何提示，直接进入应用
                        showToast(getResources().getString(R.string.cannot_finish_upgrad));
                        versionCheckFinished(true);
                    }
                }
            } else {// 如果没有新的版本，则直接跳转页面
                versionCheckFinished(true);
            }
        }
    }

    /**
     * 开启服务下载文件
     *
     * @param bean
     */
    private void toStartService(final UpDateInfo.ResultBean bean) {
        if (URLUtil.isNetworkUrl(bean.url)) {
            Intent intent = new Intent();
            intent.setClass(this, SoftwareService.class);
            intent.putExtra("url", bean.url);
            this.startService(intent);
            versionCheckFinished(true);
        } else {
            CommonQueDingDialog dialog = new CommonQueDingDialog(SplashActivity.this, "应用升级", "升级失败，请稍后重试！");
            dialog.show();
            dialog.setOnClickListener(new CommonQueDingDialog.OnClickListener() {
                @Override
                public void rightClick() {
                    if (!Utils.getVersionName(SplashActivity.this).equals(bean.num)) {
                        SplashActivity.this.finish();
                    } else {
                        versionCheckFinished(true);
                    }
                }
            });
        }
    }

    public void checkVersionFailed() {
        versionCheckFinished(false);
    }

    /**
     * 升级检测完成
     *
     * @param success
     */
    public void versionCheckFinished(boolean success) {
        if (SharePrefercesUtils.getLoginStatus(SplashActivity.this)) {
            //调用登录接口
            login();
        } else {
            //延迟一秒跳转登录注册页面
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    JumpHelper.jump(SplashActivity.this, IndexActivity.class);
                }
            }, 1000);
        }

    }

    /**
     * 下载apk
     */
    public void downFile(final String urlStr) {
        proD.show();
        new Thread() {
            public void run() {

                try {
                    URL url = new URL(urlStr);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    InputStream is = con.getInputStream();
                    // 设置进度条最大长度
                    proD.setMax(100);
                    FileOutputStream fileOutputStream = null;
                    if (is != null) {
                        File fileDir = new File(GlobalUrl.CACHE_PATH);
                        if (!fileDir.exists()) {
                            fileDir.mkdirs();
                        }
                        File file = new File(GlobalUrl.CACHE_PATH, VersonName);
                        if (!file.exists()) {
                            file.createNewFile();
                        }
                        fileOutputStream = new FileOutputStream(file);
                        byte[] b = new byte[1024];
                        int charb = -1;
                        int count = 0;
                        while ((charb = is.read(b)) != -1) {
                            fileOutputStream.write(b, 0, charb);
                            count += charb;
                            // 发送通知刷新进度条
                            down(count * 100 / con.getContentLength());

                        }
                    }
                    fileOutputStream.flush();
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }

                } catch (Exception e) {

                    e.printStackTrace();

                }
            }
        }.start();
    }

    /**
     * 下载完成，通过handler将下载对话框取消
     */
    public void down(final int jindu) {
        new Thread() {
            public void run() {

                Message msg = downloadhandler.obtainMessage();
                msg.arg1 = jindu;
                downloadhandler.sendMessage(msg);
            }
        }.start();
    }

    Handler downloadhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.arg1 != 100) {
                proD.setProgress(msg.arg1);
            } else {
                proD.cancel();
                if (!isCancel) {
                    update();
                }

            }

        }
    };

    /**
     * 安装应用
     */
    public void update() {

        isForceUpdate = false;

        Uri uri = Uri.fromFile(new File(GlobalUrl.CACHE_PATH, VersonName));
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        SplashActivity.this.finish();
    }

}
